<template>
  <div class="wrapper" >
    <div class="model" v-show="model">
      <div class="model-show" @click="model = false">
        <img :src="modelSrc" alt="" @click="model = false">
      </div>
    </div>



    <div class="ant-upload ant-upload-select ant-upload-select-picture-card" @click="openFile" >
      <span role="button" tabindex="0" class="ant-upload">
        <input id="imgFile" type="file" :accept="option.accept" multiple="multiple" @change="changeFile" style="display:none">
        <div ><div data-v-365d6523="" class="iconp">
          <i  aria-label="图标: plus" class="anticon anticon-plus">
            <svg viewBox="64 64 896 896" data-icon="plus" width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false" class="">
              <path d="M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z">
              </path>
              <path d="M176 474h672q8 0 8 8v60q0 8-8 8H176q-8 0-8-8v-60q0-8 8-8z"></path>
            </svg>
          </i>
          <div  class="ant-upload-text">上传</div></div>
        </div>
      </span>
    </div>

    <section class="pre-item">
      <div  class="ant-upload-list-picture-card-container">
        <div style="" class="ant-upload-list-item ant-upload-list-item-done ant-upload-list-item-list-type-picture-card" style="width: 138px; height: 104px; overflow: hidden; margin: 0px 8px 8px 0px; zoom: 1;">
          <img :src="preview"  class="ant-upload-list-item-image" style="width: 100%">
        </div>
      </div>
    </section>

    <a-modal :visible="previewVisible" :footer="null"  :closable="false" @cancel="handleCancel()">
      <div class="ant-modal-footer relative">
        <div style="text-align: left;float:left">滚动滑轮放大缩小图片，鼠标拖动选择区域</div>
        <slot name="footer">
          <a-button @click="handleCancel">取消</a-button>
          <a-button type="primary" @click="handleOk">裁切</a-button>
        </slot>
      </div>
      <div class="content">
      <div class="show-info">
        <div class="test test1">
          <vueCropper
            ref="cropper"
            :img="option.img"
            :outputSize="option.size"
            :outputType="option.outputType"
            :info="true"
            :full="option.full"
            :canMove="option.canMove"
            :canMoveBox="option.canMoveBox"
            :fixedBox="option.fixedBox"
            :original="option.original"
            :autoCrop="option.autoCrop"
            :autoCropWidth="option.autoCropWidth"
            :autoCropHeight="option.autoCropHeight"
            :centerBox="option.centerBox"
            :high="option.high"
            :infoTrue="option.infoTrue"
            :maxImgSize="option.maxImgSize"
            @realTime="realTime"
            @imgLoad="imgLoad"
            @cropMoving="cropMoving"
            :enlarge="option.enlarge"
            :mode="option.mode"
            :limitMinSize="option.limitMinSize"
          ></vueCropper>
        </div>



      </div>
    </div>
    </a-modal>
  </div>
</template>

<script>
  import { VueCropper } from 'vue-cropper'
  import { getFileAccessHttpUrl } from '@/api/manage'

  export default {
    name: 'ImagCropper',
    components: {
      VueCropper
    },
    props:{
      value:{
        type:String,
        required:false
      },
      width:{
        type:Number,
        required:false
      },
      height:{
        type:Number,
        required:false
      },
      isCircle:{
        type:Boolean,
        default:false,
        required:false
      }
    },
    watch:{
      value(val){
        this.$emit('change',val)
      }
    },
    data () {
      return {
        model: false,
        modelSrc: "",
        crap: false,
        previews: {},
        previewStyle1:null,
        previewVisible:false,
        cropperBlobImg:null,
        option: {
          img: this.value, // 裁剪图片的地址  空 url 地址 || base64 || blob
          outputSize: 1, // 裁剪生成图片的质量 1 0.1 - 1
          outputType: "jepg", //  裁剪生成图片的格式 jpg (jpg 需要传入jpeg)  jpeg || png || webp
          info: true, //  裁剪框的大小信息  true  true || false
          canScale: false, // 图片是否允许滚轮缩放  true  true || false
          autoCrop: true, //是否默认生成截图框 false true || false
          autoCropWidth: 200, //默认生成截图框宽度 容器的80%  0~max
          autoCropHeight: 150, //默认生成截图框高度  容器的80%  0~max
          fixed: true, //是否开启截图框宽高固定比例  true  true | false
          fixedNumber: [1, 1], //截图框的宽高比例 [1, 1]  [宽度, 高度]
          full: false, //是否输出原图比例的截图  false true | false
          fixedBox: true, //固定截图框大小 不允许改变  false true | false
          canMove: false, //上传图片是否可以移动  true  true | false
          canMoveBox: false, //截图框能否拖动 true  true | false
          original: false, //上传图片按照原始比例渲染 false true | false
          centerBox: true, //截图框是否被限制在图片里面  false true | false
          high: true, //是否按照设备的dpr 输出等比例图片  true  true | false
          infoTrue: true, //true 为展示真实输出图片宽高 false 展示看到的截图框宽高 false true | false
          maxImgSize: 2000, //限制图片最大宽度和高度 2000  0-max
          enlarge: 1, //图片根据截图框输出比例倍数 1 0-max(建议不要太大不然会卡死的呢)
          mode: "contain", //图片默认渲染方式  contain contain , cover, 100px, 100% auto
          accept:"image/gif,image/jpeg,image/jpg,image/png,image/svg"
        }
      };
    },
    methods: {
      openFile(e){
        if(e.target.id!="imgFile"){
          const file = document.getElementById("imgFile");
          file.click()
        }
      },
      changeFile(e){
        let file = e.target.files[0];
        var reader = new FileReader();
        reader.onload = e => {
          let data;
          console.log(e.target.result)
          if (typeof e.target.result === "object") {
            // 把Array Buffer转化为blob 如果是base64不需要
            data = window.URL.createObjectURL(new Blob([e.target.result]));
          } else {
            data = e.target.result;
          }
          this.option.img = data;
        };
        // 转化为blob
        reader.readAsArrayBuffer(file);
        this.previewVisible =true;
      },
      changeImg() {
        this.option.img = this.lists[~~(Math.random() * this.lists.length)].img;
      },
      startCrop() {
        // start
        this.crap = true;
        this.$refs.cropper.startCrop();
      },
      stopCrop() {
        //  stop
        this.crap = false;
        this.$refs.cropper.stopCrop();
      },
      clearCrop() {
        // clear
        this.$refs.cropper.clearCrop();
      },
      refreshCrop() {
        // clear
        this.$refs.cropper.refresh();
      },
      changeScale(num) {
        num = num || 1;
        this.$refs.cropper.changeScale(num);
      },
      rotateLeft() {
        this.$refs.cropper.rotateLeft();
      },
      rotateRight() {
        this.$refs.cropper.rotateRight();
      },
      finish(type) {
        console.log("xx:"+type)
        if (type === "blob") {
          this.$refs.cropper.getCropBlob(data => {
            var img = window.URL.createObjectURL(data);
            this.model = true;
            this.modelSrc = img;
          });
        } else {
          this.$refs.cropper.getCropData(data => {
            this.model = true;
            this.modelSrc = data;
          });
        }
      },
      // 实时预览函数
      realTime(data) {
        this.$refs.cropper.getCropBlob(blob => {
          var $URL = window.URL;
          console.log(this.isCircle)
          if(this.isCircle){
            var url = $URL.createObjectURL(blob);
            this.imageToCircle(url).then((res) => {
              //截出来的图片画成圆形
              this.cropperBlobImg = res;
            });
          }else{
            this.cropperBlobImg = blob
          }


        });
      },
      down(type) {
        // 输出
        if (type === "blob") {
          this.$refs.cropper.getCropBlob(data => {
            this.downImg = window.URL.createObjectURL(data);
            if (window.navigator.msSaveBlob) {
              var blobObject = new Blob([data]);
              window.navigator.msSaveBlob(blobObject, "demo.png");
            } else {
              this.$nextTick(() => {
                this.$refs.downloadDom.click();
              });
            }
          });
        } else {
          this.$refs.cropper.getCropData(data => {
            this.downImg = data;
            if (window.navigator.msSaveBlob) {
              var blobObject = new Blob([data]);
              window.navigator.msSaveBlob(blobObject, "demo.png");
            } else {
              this.$nextTick(() => {
                this.$refs.downloadDom.click();
              });
            }
          });
        }
      },

      uploadImg(e, num) {
        //上传图片
        // this.option.img
        var file = e.target.files[0];
        if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
          alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
          return false;
        }
        var reader = new FileReader();
        reader.onload = e => {
          let data;
          if (typeof e.target.result === "object") {
            // 把Array Buffer转化为blob 如果是base64不需要
            data = window.URL.createObjectURL(new Blob([e.target.result]));
          } else {
            data = e.target.result;
          }

          this.option.img = data;

          this.$refs.uploadImg.value = ''
        };
        // 转化为blob
        reader.readAsArrayBuffer(file);
      },
      imgLoad(msg) {
        //console.log(msg);
      },

      cropMoving(data) {
        this.option.cropData = data;
      },

      handleCancel() {
        // this.close();
        this.previewVisible = false;
      },
      handleOk(){
        let url = window.URL.createObjectURL(this.cropperBlobImg);
        this.previews.url = url

        // var blobImg = this.cropperBlobImg


        // this.previews.url = url

        let formData = new FormData();
        formData.append("file", this.cropperBlobImg);
        formData.append("biz", "temp");
        var that = this
        this.$http.post('/sys/common/upload',formData,{emulateJSON:true}).then(
          function(res){
            console.log("begin-------------------------------------");
            console.log(res)//{success: true, message: "temp/blob_1650175650582", code: 0, result: null, timestamp: 1650175650581}code: 0message: "temp/blob_1650175650582"result: nullsuccess: truetimestamp: 1650175650581__proto__: Object
            that.$emit('change', res.message)
          },function(res){
            console.log('失败')
            console.log(res)
          }
        )
        this.previewVisible=false
      },

       dataURLToBlob(dataurl){
          var arr = dataurl.split(',');
          var mime = arr[0].match(/:(.*?);/)[1];
          var bstr = atob(arr[1]);
          var n = bstr.length;
          var u8arr = new Uint8Array(n);
          while(n--){
            u8arr[n] = bstr.charCodeAt(n);
          }
          return new Blob([u8arr], {type:mime});
        },

      imageToCircle(picUrl) {
        // 通过图片地址换出圆形的图片
        let radius, diameter, canvas, ctx;
        let img = new Image();
        img.setAttribute("crossOrigin", "anonymous"); // 解决图片跨域访问失败
        img.src = picUrl;
        return new Promise((reslove) => {
          img.addEventListener(
            "load",
            () => {
              let { width, height } = img;
              if (img.width > img.height) {
                radius = height / 2;
              } else {
                radius = width / 2;
              }
              diameter = radius * 2;

              canvas = document.createElement("canvas");
              if (!canvas.getContext) {
                // 判断浏览器是否支持canvas，如果不支持在此处做相应的提示
                console.log("您的浏览器版本过低，暂不支持。");
                return false;
              }
              canvas.width = diameter;
              canvas.height = diameter;

              ctx = canvas.getContext("2d");
              ctx.clearRect(0, 0, diameter, diameter);

              // 描边
              ctx.save(); //save和restore可以保证样式属性只运用于该段canvas元素
              ctx.strokeStyle = "#eee"; //设置边线的颜色
              ctx.lineWidth = 2;
              ctx.beginPath(); //开始路径
              ctx.arc(radius, radius, radius - 5, 0, Math.PI * 2); //画一个整圆.
              ctx.stroke(); //绘制边线

              // 截圆形图
              ctx.save();
              ctx.beginPath();
              ctx.arc(radius, radius, radius - 5, 0, Math.PI * 2);
              ctx.clip();

              let x = 0,
                y = 0,
                swidth = diameter,
                sheight = diameter;

              ctx.drawImage(img, x, y, swidth, sheight, 0, 0, diameter, diameter);
              ctx.restore();
              // toDataURL()是canvas对象的一种方法，用于将canvas对象转换为base64位编码
              let dataURL = canvas.toDataURL("image/png");
              var blob = this.dataURLToBlob(dataURL);
              console.log("xxxxxxxxxxxxxxxxxxxxxx")
              console.log(dataURL)
              console.log(blob)
              reslove(blob);
            },
            false
          );
        });
      }


    },
    components: {
      VueCropper
    },
    computed:{
      preview:function(){
        return getFileAccessHttpUrl(this.value)
      }
    },
    mounted() {
      // this.changeImg();
      // this.option.img=getFileAccessHttpUrl(this.img);
      this.$set(this.previews,'url',getFileAccessHttpUrl(this.option.img))
      this.option.autoCropWidth = this.width
      this.option.autoCropHeight = this.height

    },
    model: {
      prop: "value",
      event: "change"
    }
  };
</script>

<style scoped>
  * {
    margin: 0;
    padding: 0;
  }

  .content {
    margin: auto;
    max-width: 1200px;
    /*margin-bottom: 100px;*/
  }

  .test-button {
    display: flex;
    flex-wrap: wrap;
  }

  .btn {
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    background: #fff;
    border: 1px solid #c0ccda;
    color: #1f2d3d;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin: 20px 10px 0px 0px;
    padding: 9px 15px;
    font-size: 14px;
    border-radius: 4px;
    color: #fff;
    background-color: #50bfff;
    border-color: #50bfff;
    transition: all 0.2s ease;
    text-decoration: none;
    user-select: none;
  }

  .des {
    line-height: 30px;
  }

  code.language-html {
    padding: 10px 20px;
    margin: 10px 0px;
    display: block;
    background-color: #333;
    color: #fff;
    overflow-x: auto;
    font-family: Consolas, Monaco, Droid, Sans, Mono, Source, Code, Pro, Menlo,
    Lucida, Sans, Type, Writer, Ubuntu, Mono;
    border-radius: 5px;
    white-space: pre;
  }

  .show-info {
    /*margin-bottom: 50px;*/
  }

  .show-preview {
    flex: 1;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
  }
  .preview{
    overflow: hidden;
    border:1px solid #67c23a;
    background: #cccccc;
  }


  .show-info h2 {
    line-height: 50px;
  }

  .title {
    display: block;
    text-decoration: none;
    text-align: center;
    line-height: 1.5;
    margin: 20px 0px;
    background-image: -webkit-linear-gradient(
      left,
      #3498db,
      #f47920 10%,
      #d71345 20%,
      #f7acbc 30%,
      #ffd400 40%,
      #3498db 50%,
      #f47920 60%,
      #d71345 70%,
      #f7acbc 80%,
      #ffd400 90%,
      #3498db
    );
    color: transparent;
    -webkit-background-clip: text;
    background-size: 200% 100%;
    animation: slide 5s infinite linear;
    font-size: 40px;
  }

  .test {
    height: 400px;
  }

  .model {
    position: fixed;
    z-index: 10;
    width: 100vw;
    height: 100vh;
    overflow: auto;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.8);
  }

  .model-show {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100vw;
    height: 100vh;
    text-align: center;
  }

  .model img {
    display: block;
    margin: auto;
    max-width: 80%;
    width: auto;
    user-select: none;
    background-position: 0px 0px, 10px 10px;
    background-size: 20px 20px;
    background-image: linear-gradient(
      45deg,
      #eee 25%,
      transparent 25%,
      transparent 75%,
      #eee 75%,
      #eee 100%
    ),
    linear-gradient(45deg, #eee 25%, white 25%, white 75%, #eee 75%, #eee 100%);
  }

  .c-item {
    display: block;
    padding: 10px 0;
    user-select: none;
  }

  .pre {
    display: flex;
    flex-wrap: wrap;
  }

  .pre-item {
    padding-right: 20px;
  }

  @keyframes slide {
    0% {
      background-position: 0 0;
    }
    100% {
      background-position: -100% 0;
    }
  }

  @media screen and (max-width: 1000px) {
    .content {
      max-width: 50%;
      margin: auto;
    }

    .test {
      height: 400px;
    }
  }
</style>